package com.squeekeek.util.qrcode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class GetQRPhoto extends Activity {
	public static final String TAG_IMGLOC = "imgloc";
	
	private static final int K_STATE_FROZEN = 10;
	private static final int K_STATE_RUNNING = 20;

	private File pictureFile;
	private int hCameraState = K_STATE_RUNNING;
	private List <String> usedColorModes;
	private Camera hCamera;
	private PreviewQRPhoto hPreview;
	private PictureCallback hPicture = new PictureCallback() {
		
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			FileOutputStream fos;
			
			pictureFile = getOutputImgFile();
			
			if(pictureFile == null) {
				return;
			}
			
			try {
				fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
			}
			catch(FileNotFoundException e) {
				Log.d("hPicture", "Folder DNE.");
			}
			catch(IOException e) {
				Log.d("hPicture", "Cannot save picture.");
			}
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		final Button captureBtn;
		final Button cancelBtn;
		FrameLayout preview;
		Camera.Parameters cameraParams;
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_camera_preview);
		
		try {
			hCamera = getCamera();
			
			hPreview = new PreviewQRPhoto(this, hCamera);
			preview = (FrameLayout) findViewById(R.id.frame_camerapreview);
			preview.addView(hPreview);
			
			cameraParams = hCamera.getParameters();
			usedColorModes = cameraParams.getSupportedColorEffects();
			
			if(usedColorModes != null) {
				// Set camera to grayscale
				if(usedColorModes.contains(Camera.Parameters.EFFECT_MONO)) {
					cameraParams.setColorEffect(Camera.Parameters.EFFECT_MONO);
					hCamera.setParameters(cameraParams);
				}
			}
			
			captureBtn = (Button) findViewById(R.id.btn_capture);
			cancelBtn = (Button) findViewById(R.id.btn_cancel);
			
			captureBtn.setOnClickListener(new View.OnClickListener() {
				Intent returnIntent;
				
				@Override
				public void onClick(View v) {
					returnIntent = new Intent();
					
					switch(hCameraState) {
					case K_STATE_RUNNING:
						hCamera.takePicture(null, null, hPicture);
						captureBtn.setText(R.string.actstr_acceptbtn);
						cancelBtn.setText(R.string.actstr_discardbtn);
						hCameraState = K_STATE_FROZEN;
						break;
					case K_STATE_FROZEN:
						returnIntent.putExtra(TAG_IMGLOC, pictureFile.getPath());
						setResult(RESULT_OK, returnIntent);
						finish();
						break;
					}
					
				}
				
			});
			
			cancelBtn.setOnClickListener(new View.OnClickListener() {
	
				@Override
				public void onClick(View v) {
					switch(hCameraState) {
					case K_STATE_FROZEN:
						hCamera.startPreview();
						captureBtn.setText(R.string.actstr_capturebtn);
						cancelBtn.setText(R.string.actstr_cancelbtn);
						hCameraState = K_STATE_RUNNING;
						break;
					case K_STATE_RUNNING:
						finish();
						break;
					}
				}
				
			});
		}
		catch(Exception e) {
			releaseCamera();
			finish();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		releaseCamera();
	}
	
	public static Camera getCamera() throws QRCodeException {
		Camera cam = null;
		
		try {
			cam = Camera.open();
		}
		catch(Exception e) {
			throw new QRCodeException("Cannot get camera object: " + e.getMessage());
			//Log.d("getCamera", e.getMessage());
		}
		
		return cam;
	}
	
	private void releaseCamera() {
		if(hCamera != null) {
			hCamera.release();
			hCamera = null;
		}
	}
	
	private File getOutputImgFile() {
		String timeStamp;
		File appMediaDir;
		File mediaFile;
		
		appMediaDir = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "qrcode");
		
		if(!appMediaDir.exists()) {
			if(!appMediaDir.mkdirs()) {
				//Log.d("Output", "Cannot create dir in media store.");
				return null;
			}
		}
		
		timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
		mediaFile = new File(appMediaDir.getPath() + File.separator + "qr_" + timeStamp + ".jpg");

		return mediaFile;
	}
}
